package yiran.onemonthcard.eventhandler;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import yiran.onemonthcard.system.OneMonthCardSystem;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class PlayerJoinListener implements Listener {
    private final OneMonthCardSystem OneMonthCardSystem;

    public PlayerJoinListener(OneMonthCardSystem OneMonthCardSystem) {
        this.OneMonthCardSystem = OneMonthCardSystem;
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        String playerName = player.getName();

        // 确保玩家数据已加载
        OneMonthCardSystem.OneMonthCardData data = OneMonthCardSystem.getPlayerDataMap().get(playerName);
        if (data == null) {
            data = OneMonthCardSystem.databaseManager.loadOneMonthCardData(playerName);
            if (data != null) {
                OneMonthCardSystem.getPlayerDataMap().put(playerName, data);
            } else {
                // 新玩家，无需处理
                return;
            }
        }

        // 核心修改：处理天数扣除逻辑
        if (data.isActive() && data.getLastClaimDate() != null) {
            LocalDate today = LocalDate.now();
            LocalDate lastClaim = data.getLastClaimDate();

            // 计算需要扣除的天数
            long daysToDeduct = ChronoUnit.DAYS.between(lastClaim, today);

            if (daysToDeduct > 0) {
                // 确保不扣除超过剩余天数
                int actualDeduction = (int) Math.min(daysToDeduct, data.getRemainingDays());
                data.setRemainingDays(data.getRemainingDays() - actualDeduction);

                // 更新最后领取日期为昨天（保留今天作为领取日）
                data.setLastClaimDate(today.minusDays(1));

                // 保存数据
                OneMonthCardSystem.databaseManager.saveOneMonthCardData(data);

                // 如果扣除后剩余天数<=0，处理过期
                if (data.getRemainingDays() <= 0) {
                    OneMonthCardSystem.handleCardExpiration(playerName, data);
                }
            }
        }

        // 检查并发放自动奖励（现在只处理今天的奖励）
        OneMonthCardSystem.checkAndGiveAutoReward(player);
    }
}
